from datetime import datetime
import random
import re

from flask import current_app
from flask import session

from info.libs.yuntongxun.sms import CCP
from info import constants, db
from info.models import User
from info.passport import passport_bule
from flask import request, make_response, jsonify
from info.utils.captcha.captcha import captcha
from info import redis_store
from info.utils.response_code import RET





@passport_bule.route("/logout", methods=["GET", "POST"])
def logout():
    session.pop("user_id",None)
    session.pop("nike_name",None)
    session.pop("mobile",None)
    session.pop("is_admin",None)
    return jsonify(errno = RET.OK,errmsg = "退出成功")


@passport_bule.route("/login", methods=["GET", "POST"])
def login():
    mobile = request.json.get("mobile")
    password = request.json.get("password")
    # user = None00
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="请注册")
    if not user.check_password(password):
        return jsonify(errno=RET.PWDERR, errmsg="请输入正确的密码")

    session["user_id"] = user.id
    session["nike_name"] = user.nick_name
    session["mobile"] = user.mobile
    user.last_login = datetime.now()
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="登陆成功")


@passport_bule.route("/register", methods=["GET", "POST"])
def register():
    mobile = request.json.get("mobile")
    # 获取短信验证码
    smscode = request.json.get("smscode")
    password = request.json.get("password")
    # 获取客户端验证码
    real_sms_code = redis_store.get("sms_code_" + mobile)

    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码已经过期")
    if smscode != real_sms_code:
        return jsonify(errno=RET.PARAMERR, errmsg="请输入正确的短信验证码")

    user = User()
    user.mobile = mobile
    user.password = password
    user.nick_name = mobile
    user.last_login = datetime.now()

    db.session.add(user)
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="注册成功")


@passport_bule.route("/sms_code", methods=["GET", "POST"])
def sms_code():
    # 获取手机
    mobile = request.json.get("mobile")
    # 获取图片验证码
    image_code = request.json.get("image_code")
    # 获取图片验证码的id
    image_code_id = request.json.get("image_code_id")

    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="请输入参数")

    if not re.match("1[3456789]\d{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="请输入正确的手机号")

    real_image_code = redis_store.get("image_code_" + image_code_id)

    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码已经过期")

    if image_code.lower() != real_image_code.lower():
        return jsonify(errno=RET.PARAMERR, errmsg="请输入正确的验证码")

    random_sms_code = "%06d" % random.randint(0, 999999)
    redis_store.set("sms_code_" + mobile, random_sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    print("短信验证码的内容 = " + random_sms_code)

    # 发送
    # statuCode = CCP().send_template_sms(mobile,[random_sms_code,5],1)
    # if statuCode != 0:
    #     return jsonify(erron = RET.THIRDERR,errmsg = "短信发送失败")


    return jsonify(errno=RET.OK, errmsg="发送短信成功")


@passport_bule.route("/image_code")
def image_code():
    print("前端请求的地址" + request.url)
    code_id = request.args.get("code_id")

    name, text, image = captcha.generate_captcha()

    print("图片验证码的内容" + text)

    redis_store.set("image_code_" + code_id, text, 300)

    resp = make_response(image)

    resp.headers['Content-Type'] = 'image/jpg'

    return resp
